package fastwave.cloud.demo.fastwave.biz.publisher.config;

import fastwave.cloud.demo.fastwave.biz.publisher.domain.MsgLog;
import fastwave.cloud.demo.fastwave.biz.publisher.service.MsgLogService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.SerializerMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.UUID;

/**
 * 消息可靠投递编码实现
 * <p>Title: TemplateReliableConfig</p>
 * <p>Description: </p>
 *
 * @author: dwLiu
 * @date: 2020/4/8 21:47
 */
@Configuration
public class TemplateReliableConfig {

    @Autowired
    private MsgLogService msgLogService;

    @Bean(name = "TemplateReliable")
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setMessageConverter(new SerializerMessageConverter());

        //在exchange环节返回状态，是否有交换机，返回true,false
        rabbitTemplate.setConfirmCallback((CorrelationData correlationData, boolean ack, String cause) -> {
            if (ack) {
                MsgLog msgLog = new MsgLog();
                msgLog.setMsgId(correlationData.getId());
                msgLog.setStatus(1);
                msgLogService.updateById(msgLog);
            }
        });
        //在正确找到交换机（exchange）后，向队列（queue）路由的时候，没有正确的路由也就是没有任何的队列路由到队列区里面
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                MsgLog msgLog = new MsgLog();
                Date curTime = new Date();
                msgLog.setMsgId(UUID.randomUUID().toString());
                msgLog.setStatus(4);
                msgLog.setExchange(exchange);
                msgLog.setMsg(message.toString());
                msgLog.setTryCount(0);
                msgLog.setRoutingKey(routingKey);
                msgLog.setCreateTime(curTime);
                msgLog.setUpdateTime(curTime);
                msgLog.setNextTryTime(curTime);
                msgLogService.save(msgLog);
            }
        });

        return rabbitTemplate;
    }
}
